package com.zmn.plat.services.impl.push;

import java.util.List;
import java.util.Objects;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dto.PushMsgDTO;
import com.zmn.common.dto.ResultDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.manager.mq.utils.MQPushUtil;
import com.zmn.plat.manager.constant.MsgTemplateConsts;
import com.zmn.plat.manager.constant.ZmnSmsConsts;
import com.zmn.plat.model.entity.message.MsgTemplate;
import com.zmn.plat.model.entity.message.MsgTemplateGroup;
import com.zmn.plat.model.entity.message.MsgTemplateQuery;
import com.zmn.plat.model.entity.push.ZmnSms;
import com.zmn.plat.services.interfaces.message.MsgTemplateGroupService;
import com.zmn.plat.services.interfaces.message.MsgTemplateService;
import com.zmn.plat.services.interfaces.push.ZmnSmsService;

@Service
public class ZmnSmsServiceImpl implements ZmnSmsService {

    private Logger logger = LoggerFactory.getLogger(ZmnSmsServiceImpl.class);

    @Resource
    MsgTemplateGroupService msgTemplateGroupService;

    @Resource
    MsgTemplateService msgTemplateService;

    @Override
    public Integer sendZmnSmsInfo(ZmnSms zmnSms) {
        MsgTemplateGroup msgTemplateGroup = msgTemplateGroupService.findByKey(zmnSms.getGroupId());
        MsgTemplate msgTemplate;
        if (Objects.equals(msgTemplateGroup.getStatus(), GlobalConsts.NO)) {
            return ZmnSmsConsts.MSG_SEND_ERROR_GROUP_HIDDEN;
        }

        // 如果渠道城市ID都有，发送渠道城市模板
        if (NumberUtil.isPositiveInteger(zmnSms.getChannelId()) && NumberUtil.isPositiveInteger(zmnSms.getCityId())) {
            msgTemplate = msgTemplateService.findByGroupIdAndTypeAndChannelIdAndCityId(zmnSms.getGroupId(), MsgTemplateConsts.MSG_TEMP_TYPE_CHANNEL_CITY, zmnSms.getChannelId(), zmnSms.getCityId());
            if (Objects.nonNull(msgTemplate)) {
                return this.sendSmsByTemplateAndSmsInfo(msgTemplate, zmnSms);
            }
        }
        // 只有渠道发送渠道模板
        if (NumberUtil.isPositiveInteger(zmnSms.getChannelId())) {
            msgTemplate = msgTemplateService.findByGroupIdAndTypeAndChannelIdAndCityId(zmnSms.getGroupId(), MsgTemplateConsts.MSG_TEMP_TYPE_CHANNEL, zmnSms.getChannelId(), null);
            if (Objects.nonNull(msgTemplate)) {
                return this.sendSmsByTemplateAndSmsInfo(msgTemplate, zmnSms);
            }
        }

        // 只有城市发送城市模板
        if (NumberUtil.isPositiveInteger(zmnSms.getChannelId())) {
            msgTemplate = msgTemplateService.findByGroupIdAndTypeAndChannelIdAndCityId(zmnSms.getGroupId(), MsgTemplateConsts.MSG_TEMP_TYPE_CITY, null, zmnSms.getCityId());
            if (Objects.nonNull(msgTemplate)) {
                return this.sendSmsByTemplateAndSmsInfo(msgTemplate, zmnSms);
            }
        }

        // 则发送通用模板
        MsgTemplateQuery query = new MsgTemplateQuery();
        query.setGroupId(zmnSms.getGroupId());
        query.setTemplateType(MsgTemplateConsts.MSG_TEMP_TYPE_CURRENCY);
        List<MsgTemplate> msgTemplateList = msgTemplateService.listByQuery(query);
        if (msgTemplateList.size() != 1) {
            return ZmnSmsConsts.MSG_SEND_CURRENCY_NONE_ERROR;
        }
        msgTemplate = msgTemplateList.get(0);
        return this.sendSmsByTemplateAndSmsInfo(msgTemplate, zmnSms);

    }

    private Integer sendSmsByTemplateAndSmsInfo(MsgTemplate msgTemplate, ZmnSms zmnSms) {
        // 判断模板是否有配置微信，如果有配置微信，则发微信消息
        if (Objects.nonNull(msgTemplate.getWechatMessage()) && Objects.nonNull(zmnSms.getOpenId())) {
            if (Objects.isNull(zmnSms.getOpenId())) {
                return ZmnSmsConsts.MSG_SEND_NO_OPENID_ERROR;
            }
            if (Objects.isNull(msgTemplate.getWechatTempId())) {
                return ZmnSmsConsts.MSG_NO_WEICHART_TEMPLATE_ID_ERROR;
            }
            ResultDTO resultDTO;
            if (Objects.nonNull(zmnSms.getPagePath()) && Objects.nonNull(zmnSms.getAppId())) {
                resultDTO = Objects.isNull(zmnSms.getToken())
                    ? MQPushUtil.sendWeChatTemplateInfoAndJumpMiniProgram(zmnSms.getOpenId(), msgTemplate.getWechatTempId(), zmnSms.getAppId(), zmnSms.getPagePath(), zmnSms.getWeChartParams())
                    : MQPushUtil.sendWeChatTemplateInfoAndJumpMiniProgramByToken(zmnSms.getOpenId(), msgTemplate.getWechatTempId(), zmnSms.getAppId(), zmnSms.getPagePath(), zmnSms.getWeChartParams(),
                        zmnSms.getToken());
                logger.info("微信参数params：" + zmnSms.getWeChartParams() + ",PagePath:" + zmnSms.getPagePath() + ",OpenId:" + zmnSms.getOpenId() + ",WechatTempId:" + msgTemplate.getWechatTempId()
                    + ",AppId:" + zmnSms.getAppId());
            } else {
                if (Objects.nonNull(zmnSms.getUrl())) {
                    resultDTO =
                        Objects.isNull(zmnSms.getToken()) ? MQPushUtil.sendWeChatTemplateInfoAndJumpUrl(zmnSms.getOpenId(), msgTemplate.getWechatTempId(), zmnSms.getUrl(), zmnSms.getWeChartParams())
                            : MQPushUtil.sendWeChatTemplateInfoAndJumpUrlByToken(zmnSms.getOpenId(), msgTemplate.getWechatTempId(), zmnSms.getUrl(), zmnSms.getWeChartParams(), zmnSms.getToken());
                    logger.info("微信参数params：" + zmnSms.getWeChartParams() + ",Url:" + zmnSms.getUrl() + ",OpenId:" + zmnSms.getOpenId() + ",WechatTempId:" + msgTemplate.getWechatTempId());
                } else {
                    resultDTO = Objects.isNull(zmnSms.getToken()) ? MQPushUtil.sendWeChatTemplateInfo(zmnSms.getOpenId(), msgTemplate.getWechatTempId(), zmnSms.getWeChartParams())
                        : MQPushUtil.sendWeChatTemplateInfoByToken(zmnSms.getOpenId(), msgTemplate.getWechatTempId(), zmnSms.getWeChartParams(), zmnSms.getToken());
                    logger.info("微信参数params：" + zmnSms.getWeChartParams() + ",OpenId:" + zmnSms.getOpenId() + ",WechatTempId:" + msgTemplate.getWechatTempId());
                }
            }
            if (resultDTO.getStatusBool()) {
                return ZmnSmsConsts.MSG_SEND_SUCCESS;
            }
            logger.info(resultDTO.getMessage());
            return ZmnSmsConsts.MSG_SEND_WEICHART_TERROR;
        }
        if (Objects.isNull(msgTemplate.getMessage())) {
            return ZmnSmsConsts.MSG_NO_TEMPLATE_MESSAGE_ERROR;
        }
        // 发送创蓝短信
        if (Objects.equals(msgTemplate.getWay(), MsgTemplateConsts.MSG_TEMP_WAY_CL)) {
            // 拼装签名
            String msg = Objects.isNull(msgTemplate.getMessageMark()) ? msgTemplate.getMessage() : "【" + msgTemplate.getMessageMark() + "】" + msgTemplate.getMessage();
            ResultDTO resultDTO = MQPushUtil.sendChuangLanTemplateInfoByTime(zmnSms.getParams(), msg, DateUtil.getNowFormatted(DateUtil.FORMAT_DATETIME3), msgTemplate.getMessageAccount(),
                msgTemplate.getMessagePwd(), msgTemplate.getMessageType());
            logger.info("创蓝参数params：" + zmnSms.getParams() + ",msg:" + msg + ",time:" + DateUtil.getNowFormatted(DateUtil.FORMAT_DATETIME3));

            if (resultDTO.getStatusBool()) {
                return ZmnSmsConsts.MSG_SEND_SUCCESS;
            }
            logger.info(resultDTO.getMessage());
            return ZmnSmsConsts.MSG_SEND_CN_TERROR;
        }
        // 发送阿里短信
        if (Objects.equals(msgTemplate.getWay(), MsgTemplateConsts.MSG_TEMP_WAY_Ali)) {
            String day = DateUtil.getNowFormatted(DateUtil.FORMAT_DATE);

            String id = new StringBuilder(zmnSms.getMobile()).append(",").append(msgTemplate.getMessageMark()).toString();
            PushMsgDTO sms = new PushMsgDTO(id, msgTemplate.getWayId(), JSON.toJSONString(zmnSms.getJsonObject()));

            String key = new StringBuilder(zmnSms.getMobile()).append("_").append(day).toString();
            ResultDTO resultDTO = MQPushUtil.sendAliSmsInfo(key, sms);
            if (resultDTO.getStatusBool()) {
                return ZmnSmsConsts.MSG_SEND_SUCCESS;
            }
            logger.info(resultDTO.getMessage());
            return ZmnSmsConsts.MSG_SEND_ALI_TERROR;
        }
        // 发送掌上通短信
        if (Objects.equals(msgTemplate.getWay(), MsgTemplateConsts.MSG_TEMP_WAY_ZST)) {
            ResultDTO resultDTO = MQPushUtil.sendBizSmsInfo(zmnSms.getMobile(), msgTemplate.getMessage());
            if (resultDTO.getStatusBool()) {
                return ZmnSmsConsts.MSG_SEND_SUCCESS;
            }
            logger.info(resultDTO.getMessage());
            return ZmnSmsConsts.MSG_SEND_ZST_TERROR;
        }
        return ZmnSmsConsts.MSG_SEND_ERROR;
    }
}
